import os

def crc32_custom(data, poly=0x04c11db7, init_crc=0x00000000, ref_in=False, ref_out=False, xor_out=0x00000000):
    """
    自定义CRC32计算函数
    poly: 多项式值 (0x04c11db7)
    init_crc: 初始值 (0x00000000)
    ref_in: 输入反转 (False)
    ref_out: 输出反转 (False)
    xor_out: 输出异或值 (0x00000000)
    """
    
    def reflect_byte(byte_val):
        """反转字节的位顺序"""
        result = 0
        for i in range(8):
            if byte_val & (1 << i):
                result |= (1 << (7 - i))
        return result
    
    def reflect_32(val):
        """反转32位数据的位顺序"""
        result = 0
        for i in range(32):
            if val & (1 << i):
                result |= (1 << (31 - i))
        return result
    
    crc = init_crc
    
    for byte in data:
        if ref_in:
            byte = reflect_byte(byte)
        
        crc ^= (byte << 24)
        
        for _ in range(8):
            if crc & 0x80000000:
                crc = ((crc << 1) ^ poly) & 0xFFFFFFFF
            else:
                crc = (crc << 1) & 0xFFFFFFFF
    
    if ref_out:
        crc = reflect_32(crc)
    
    return crc ^ xor_out

def calculate_firmware_crc32(file_path):
    """计算固件文件的CRC32值"""
    try:
        with open(file_path, 'rb') as file:
            file_content = file.read()
            # 使用自定义参数：多项式0x04c11db7，初值0，不反转，不异或
            crc32_value = crc32_custom(
                data=file_content,
                poly=0x04c11db7,
                init_crc=0x00000000,
                ref_in=False,
                ref_out=False,
                xor_out=0x00000000
            )
            return crc32_value
    except FileNotFoundError:
        print(f"错误：找不到文件 {file_path}")
        return None
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return None

def save_crc32_to_file(crc32_value, firmware_file, output_file):
    """将CRC32结果保存到txt文件"""
    try:
        with open(output_file, 'w', encoding='utf-8') as file:
            file.write(f"0x{crc32_value:08X}\n")
        print(f"CRC32结果已保存到: {output_file}")
    except Exception as e:
        print(f"保存文件时发生错误：{e}")

def main():
    firmware_file = "firmware.bin"
    output_file = "crc32.txt"
    
    # 检查固件文件是否存在
    if not os.path.exists(firmware_file):
        print(f"错误：找不到固件文件 {firmware_file}")
        print("请确保firmware.bin文件在当前目录中")
        return
    
    print(f"正在计算 {firmware_file} 的CRC32...")
    print("CRC32参数：多项式=0x04C11DB7，初值=0x00000000，不反转，不异或")
    
    # 计算CRC32
    crc32_value = calculate_firmware_crc32(firmware_file)
    
    if crc32_value is not None:
        print(f"CRC32: 0x{crc32_value:08X}")
        print(f"CRC32 (十进制): {crc32_value}")
        
        # 保存结果到文件
        save_crc32_to_file(crc32_value, firmware_file, output_file)
    else:
        print("CRC32计算失败")

if __name__ == "__main__":
    main()